<template>
  <el-form ref="form" :model="data" v-loading="loading" :rules="rules" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(8,18,33, 0.8)" label-width="100px">
    <el-form-item label="巡检批次号" prop="task_code">
      <el-input v-model.trim="data.task_code" placeholder="请填写巡检批次号" />
    </el-form-item>
    <el-form-item label="巡检任务名称" label-width="120px" prop="task_name">
      <el-input v-model.trim="data.task_name" placeholder="请填写巡检任务名称" />
    </el-form-item>

    <el-form-item label="所属项目" prop="project_id">
      <el-select v-model="data.project_id" placeholder="请选择所属项目" clearable @change="select_project" class="filter-item">
        <el-option v-for="(project,index) in project_list" :key="index" :label="project.title" :value="project.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属建筑" prop="building_id">
      <el-select v-model="data.building_id" placeholder="请选择所属建筑" @change="select_building" clearable class="filter-item">
        <el-option v-for="(building,index) in building_list" :key="index" :label="building.title" :value="building.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属楼层" prop="floor_id">
      <el-select v-model.trim="data.floor_id" placeholder="请选择所属楼层" clearable class="filter-item">
        <el-option v-for="(floor,index) in floor_list" :key="index" :label="floor.title" :value="floor.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="巡检员" prop="inspector_id">
      <el-select v-model.trim="data.inspector_id" placeholder="请选择巡检员" clearable class="filter-item">
        <el-option v-for="(admin,index) in admin_list" :key="index" :label="admin.nickname" :value="admin.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="计划巡检时间" prop="scheduled_time" label-width="120px">
      <el-date-picker v-model.trim="data.scheduled_time" value-format="yyyy-MM-dd" placeholder="请填写计划巡检时间" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" :disabled="$store.state.settings.ajaxButton" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { create } from '@/api/inspectiontask'
import { getToken } from '@/utils/auth'
import { commonApi } from '@/api/common' // 公共接口

export default {
  name: 'inspectiontaskCreate',
  components: { },
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    project_list: {
      type: Array,
      default: () => {
        return []
      }
    },
    admin_list: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      headerObj: {
        'Authorization': 'Bearer ' + getToken()
      },
      rules: {
        task_name: [ 
          { required: true, message: "请输入巡检任务名称", trigger: "blur" }
        ], 
        customer_id: [ 
          { required: true, message: "请输入所属客户", trigger: "blur" }
        ], 
        project_id: [ 
          { required: true, message: "请输入所属项目", trigger: "blur" }
        ], 
        inspector_id: [ 
          { required: true, message: "请选择巡检员", trigger: "blur" }
        ], 
        scheduled_time: [
          { required: true, message: "请选择计划巡检时间", trigger: "blur" }
        ]
      },
      building_list: [],
      floor_list: [],
      data: {
        task_code: '',
        task_name: '',
        customer_id: '',
        project_id: '',
        project_name: '',
        building_id: '',
        building_name: '',
        floor_id: '',
        floor_name: '',
        inspector_id: '',
        inspector_name: '',
        scheduled_time: '',
      }
    }
  },
  methods: {
    // 根据ID获取项目名称
    getProjectName(projectId) {
      const project = this.project_list.find(item => item.id === projectId)
      return project ? project.title : ''
    },

    // 根据ID获取建筑名称
    getBuildingName(buildingId) {
      const building = this.building_list.find(item => item.id === buildingId)
      return building ? building.title : ''
    },

    // 根据ID获取楼层名称
    getFloorName(floorId) {
      const floor = this.floor_list.find(item => item.id === floorId)
      return floor ? floor.title : ''
    },

    // 根据ID获取巡检员名称
    getInspectorName(inspectorId) {
      const admin = this.admin_list.find(item => item.id === inspectorId)
      return admin ? admin.nickname : ''
    },

    select_project(value) {
      if (!value) {
        this.building_list = []
        this.data.building_id = '' // 清空建筑选择
        this.data.building_name = '' // 清空建筑名称
        this.data.project_name = '' // 清空项目名称
        return
      }
      
      // 设置项目名称
      this.data.project_name = this.getProjectName(value)
      
      this.loading = true
      commonApi.get_building({ project_id: value }).then(response => {
        this.building_list = response.data
      }).catch(error => {
        console.error('获取建筑列表失败:', error)
        this.building_list = []
      }).finally(() => {
        this.loading = false
      })
    },

    select_building(value) {
      if (!value) {
        this.data.building_id = '' // 清空建筑选择
        this.data.building_name = '' // 清空建筑名称
        this.floor_list = []
        this.data.floor_id = '' // 清空楼层选择
        this.data.floor_name = '' // 清空楼层名称
        return
      }
      
      // 设置建筑名称
      this.data.building_name = this.getBuildingName(value)
      
      this.loading = true
      commonApi.get_floor({ building_id: value }).then(response => {
        this.floor_list = response.data
      }).catch(error => {
        console.error('获取楼层列表失败:', error)
        this.floor_list = []
      }).finally(() => {
        this.loading = false
      })
    },

    // 监听楼层选择变化
    select_floor(value) {
      this.data.floor_name = this.getFloorName(value)
    },

    // 监听巡检员选择变化
    select_inspector(value) {
      this.data.inspector_name = this.getInspectorName(value)
    },
    
    submit() {
      const thiz = this

      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }

        // 确保所有名称字段都有值
        if (this.data.project_id) {
          this.data.project_name = this.getProjectName(this.data.project_id)
        }
        if (this.data.building_id) {
          this.data.building_name = this.getBuildingName(this.data.building_id)
        }
        if (this.data.floor_id) {
          this.data.floor_name = this.getFloorName(this.data.floor_id)
        }
        if (this.data.inspector_id) {
          this.data.inspector_name = this.getInspectorName(this.data.inspector_id)
        }

        create({
          task_code: this.data.task_code,
          task_name: this.data.task_name,
          customer_id: this.data.customer_id,
          project_id: this.data.project_id,
          project_name: this.data.project_name,
          building_id: this.data.building_id,
          building_name: this.data.building_name,
          floor_id: this.data.floor_id,
          floor_name: this.data.floor_name,
          inspector_id: this.data.inspector_id,
          inspector_name: this.data.inspector_name,
          scheduled_time: this.data.scheduled_time,
        }).then(response => {
          this.$store.commit('settings/SET_AJAX_BUTTON', true)
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1500,
            onClose() {
              if (thiz.$refs.form !== undefined) {
                thiz.$refs.form.resetFields()
              }
              thiz.item.dialogVisible = false
            }
          })
        })
      })
    }
  },

  watch: {
    'data.floor_id': function(newVal) {
      if (newVal) {
        this.data.floor_name = this.getFloorName(newVal)
      } else {
        this.data.floor_name = ''
      }
    },
    'data.inspector_id': function(newVal) {
      if (newVal) {
        this.data.inspector_name = this.getInspectorName(newVal)
      } else {
        this.data.inspector_name = ''
      }
    }
  }
}
</script>